const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const { renderTimetableToImage, transformCourseToSubscribe } = require('../renderTimetable');

// 确保目录存在
const imageDir = path.join(__dirname, '..', 'public', 'images');
fs.mkdirSync(imageDir, { recursive: true });

router.post('/', async (req, res) => {
  // 定义配置参数
  let options = {
    shop_name: "", //必填 店铺名称 成禾美学空间
    plan_date: "", //必填 计划周期 06月课表 06/29~07/05
    mini_qrcode: "", //必填 小程序Logo CDN地址 
    header_bg_image: "", //非必填 头部背景图
    tips: "", //非必填 备注
    courses: "" //必填JSON字符串 /mini/getWeekCourseList list转换为JSON字符串
  }
  try {
    const browser = req.app.locals.browser;
    let reqBody = req.body;
    if(!reqBody.shop_name){
      res.json({
        code: 2,
        msg: '【shop_name】 不能为空'
      });
      return 
    }
    if(!reqBody.plan_date){
      res.json({
        code: 2,
        msg: '【plan_date】 不能为空'
      });
      return
    }
    if(!reqBody.mini_qrcode){
      res.json({
        code: 2,
        msg: '【mini_qrcode】 不能为空'
      });
      return
    }
    if(!reqBody.courses){
      res.json({
        code: 2,
        msg: '【courses】 不能为空'
      });
      return
    }
    // const share_sub_url = await transformCourseToSubscribe(req.body.courses, 'https://node.kewenkeji.cn');
    const imageBuffer = await renderTimetableToImage(req.body, browser);
    // const filename = `${uuidv4()}.png`;
    // const filepath = path.join(imageDir, filename);
    // fs.writeFileSync(filepath, imageBuffer);
    // const imageUrl = `/images/${filename}`;
    res.json({ 
      code: 1, 
      data: {
         share_img_buffer: imageBuffer.toString('base64'),  
         share_sub_url: '',
      }
    });
  } catch (e) {
    console.error(e);
    res.status(500).send('生成失败');
  }
});

module.exports = router;
